#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define N 7

int arr[] = {7, 3, 4, 2, 6, 8, 1};

struct param {
    int start;
    int end;
};

void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

void *select_sort(void *arg) {
    struct param *param;
    param = (struct param *)arg;

    int i, j;
    for(i = param->start; i < param->end - 1; i ++) {
        int idx = i;
        for(j = i + 1; j < param->end; j ++) {
            if(arr[idx] > arr[j]) {
                idx = j;
            }
        }
        swap(arr + i, arr + idx);
    }
}

void merge_sort(int res[]) {
    int i = 0, j = N / 2, k = 0;
    while(i < N / 2 && j < N) {
        if(arr[i] <= arr[j]) res[k ++] = arr[i ++];
        else res[k ++] = arr[j ++];
    }
    while(i < N / 2) res[k ++] = arr[i ++];
    while(j < N) res[k ++] = arr[j ++];
}

void print_array(int arr[]) {
    for(int i = 0; i < N; i ++) printf("%d ", arr[i]);
    printf("\n");
}

void main() {
    printf("before sort: ");
    print_array(arr);

    pthread_t worker[2];
    struct param *param[2];
    for(int i = 0; i < 2; i ++) {
        // 创建线程，执行选择排序
        struct param *param;
        param = &param[i];
        if(!i) {
            param->start = 0;
            param->end = N / 2;
        } else {
            param->start = N / 2;
            param->end = N;
        }
        pthread_create(&worker[i], NULL, select_sort, param);
    }

    // 等待线程执行完毕
    for(int i = 0; i < 2; i ++) {
        pthread_join(worker[i], NULL);
    }
    printf("after select_sort: ");
    print_array(arr);

    // 归并
    int res[N]; 
    merge_sort(res);
    printf("after merge_sort: ");
    print_array(res);
}